package com.leunpha.mini.net;

import com.leunpha.mini.net.factory.ClientFactory;
import com.leunpha.mini.net.factory.RequestFactory;
import com.leunpha.mini.utils.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;

import java.io.*;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

/**
 * User: zhoujingjie
 * Date: 14-5-13
 * Time: 下午1:30
 */
public class MiniRequest implements Request {
    private static final Log log = LogFactory.getLog(MiniRequest.class);
    private RequestType requestType = RequestType.GET;
    private String uri;
    private HttpClient client;
    private HttpRequestBase method;
    private int statusCode;
    private String encoding;
    private int timeOut;
    private HttpResponse response;
    public MiniRequest(String uri) {
        this(uri,5000);
    }
    public MiniRequest(String uri,int timeout){
        this.uri = uri;

        this.method=RequestFactory.getMethod(requestType,uri);
        this.client = ClientFactory.getInstance();
        this.timeOut =timeout;
    }
    public void execute() throws IOException {
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(timeOut)
                .setSocketTimeout(timeOut)
                .build();
        method.setConfig(config);
        method.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36");
     //   method.addHeader("Accept-Encoding","gzip,deflate,sdch");
        response = this.client.execute(method);
        this.statusCode = response.getStatusLine().getStatusCode();
    }

    @Override
    public void close() {
        method.releaseConnection();
    }

    public void setRequestHeader(String name,String value){
        method.addHeader(name,value);
    }

    public int getStatusCode(){
        return statusCode;
    }
    protected String matcher(String reg,String str){
        Matcher matcher = Pattern.compile(reg,Pattern.DOTALL).matcher(str);
        if(matcher.find()){
            return matcher.group(1);
        }
        return null;
    }

    public String getPageEncoding(String result){
        if(encoding == null){
            String reg = "<meta.*?charset\\s*=\\s*[\'|\\\"]?(\\w)[\'|\\\"].*?>";
            encoding = matcher(reg,result);
        }
        if(encoding == null){
            encoding = "UTF-8";
        }
        return encoding;
    }

    public String getContentTypeEncoding(){
        Charset charset =  ContentType.getOrDefault(response.getEntity()).getCharset();
        if(charset!=null){
            this.encoding = charset.displayName();
        }
        return encoding;
    }

    public String getResponseByAsString() throws IOException {
        InputStream is = getResponseAsStream();
        //Header header = method.getRequestHeader("Content-Encoding");
        //ContentType.getOrDefault(response.getEntity()).getMimeType()

        /*if(header!=null && header.getValue().contains("gzip")){
            is = new GZIPInputStream(is);
        }*/
        getContentTypeEncoding();
        if(this.encoding ==null){
            this.encoding = "UTF-8";
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(is),this.encoding));
        StringBuilder result = new StringBuilder(is.available());
        String line;
        while ((line=reader.readLine())!=null){
            result.append(line);
        }

        IOUtils.close(is);
        IOUtils.close(reader);
        close();
        return result.toString();
    }



    public InputStream getResponseAsStream() throws IOException {

        if(statusCode>=200 && statusCode<300){
            return response.getEntity().getContent();
        }else{
            return null;
        }
    }

    /**
     * 获取返回头
     *
     * @param key
     * @return
     */
    @Override
    public String getResponseHeader(String key) {
        return null;
    }

    /**
     * 获取长度
     *
     * @return
     */
    @Override
    public long getContentLength() {
        return response.getEntity().getContentLength();
    }

}
